package com.itzhoun.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.itzhoun.client.MyMQTTClient;
import com.itzhoun.msg.MqttMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author zhounan
 * @date 2025/02/07 8:59
 * @Description
 */
@RestController
@RequestMapping("/sun/mqtt")
public class MqttController {

    public static Logger logger = LoggerFactory.getLogger(MqttController.class);

    Queue<String> msgQueue = new LinkedList<>();
    int count = 1;

    @Resource
    private MyMQTTClient mqttClient;
    @Value("${mqtt.topic2}")
    String topic2;

    @PostMapping("/getMsg")
    public synchronized void mqttMsg(@RequestBody MqttMsg mqttMsg){
        logger.info("队列元素数量:{}", msgQueue.size());
        logger.info("消息内容name:{}. content:{}", mqttMsg.getName(), mqttMsg.getContent());

        mqttMsg.setTime(DateUtil.now());
        mqttMsg.setContent(mqttMsg.getContent() + "-后台编号:" + count);
        count++;

        JSON parse = JSONUtil.parse(mqttMsg);
        String sendMsg = parse.toString();

        boolean offer = msgQueue.offer(sendMsg);
        if (offer){
            //发布消息，，
            mqttClient.publish(msgQueue.poll(), topic2);
            logger.info("发布消息时间:{}", DateUtil.now());
        }

        logger.info("队列元素数量:{}", msgQueue.size());
    }
}
